﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Core
{
    public static partial class status
    {
        public static dynamic deleteStatus(int rid)
        {
            var sql = new Sql.SqlDataContext();
            var s = sql.Status.FirstOrDefault(row => row.rid == rid);
            if (s == null) return new
            {
                success = false,
                msg = "状态不存在"
            };

            if (s.status >= 3 && !s.god)
            {
                // Update US
                var us = sql.UserStatistics.FirstOrDefault(row => row.username == s.username);
                if (us != null) user.deleteUserStatistics(us, s.status);

                // Update PS
                var ps = sql.ProblemStatistics.FirstOrDefault(row => row.pid == s.pid);
                if (ps != null) problem.deleteProblemStatistics(ps, s.status);

                // Update Solve
                var so = sql.Solve.FirstOrDefault(row => row.username == s.username && row.pid == s.pid);
                if (so != null)
                {
                    --so.submit;
                    if (s.status == 3)
                    {
                        --so.accept;
                        if (so.bestRid == s.rid)
                        {
                            var newBest = (from s2 in sql.Status
                                           where s2.username == s.username && s2.pid == s.pid && s2.status == 3 && s2.rid != s.rid && !s2.god
                                           orderby s2.exeTime, s2.exeMem, s2.code.Length, s2.submitTime
                                           select s2).FirstOrDefault();
                            so.bestRid = newBest == null ? null : (int?)newBest.rid;
                        }
                    }
                }
            }

            // Delete Status
            sql.Status.DeleteOnSubmit(s);
            sql.SubmitChanges();
            return new
            {
                success = true
            };
        }
    }
}
